package com.ty.filter;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import cn.smart.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class TraceIdFilter implements GlobalFilter {

    private static final String TRACE_ID = "traceId";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String TRACE_ID_VALUE = request.getHeaders().getFirst(TRACE_ID);
        if (ObjectUtil.isEmpty(TRACE_ID_VALUE)) {
            TRACE_ID_VALUE = IdUtil.fastUUID();
            ServerHttpRequest request2 = request.mutate().header(TRACE_ID, TRACE_ID_VALUE).build();
            ServerWebExchange exchange2 = exchange.mutate().request(request2).build();
            return chain.filter(exchange2);
        }else {
           // request.getHeaders().add(TRACE_ID, TRACE_ID_VALUE);
            return chain.filter(exchange);
        }

    }
}